package com.example.service;

import cn.hutool.core.date.DateUtil;
import com.example.common.enums.RoleEnum;
import com.example.entity.Account;
import com.example.entity.Apply;
import com.example.entity.Student;
import com.example.mapper.ApplyMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 请假信息表业务处理
 **/
@Service
public class ApplyService {

    @Resource
    private ApplyMapper applyMapper;

    /**
     * 新增
     */
    public void add(Apply apply) {
        applyMapper.insert(apply);
    }

    /**
     * 删除
     */
    public void deleteById(Integer id) {
        applyMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        // 使用 Java 21 增强的 Stream API
        ids.forEach(applyMapper::deleteById);
    }
    /**
     * 修改
     */
    public void updateById(Apply apply) {
        applyMapper.updateById(apply);
    }

    /**
     * 根据ID查询
     */
    public Apply selectById(Integer id) {
        return applyMapper.selectById(id);
    }

    /**
     * 查询所有
     * 添加权限控制：学生只能查看自己的请假申请
     */
    public List<Apply> selectAll(Apply apply) {
        List<Apply> list = applyMapper.selectAll(apply);
        
        // 获取当前登录用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser != null && RoleEnum.STUDENT.name().equals(currentUser.getRole())) {
            // 学生只能看到自己的请假申请
            Student student = (Student) currentUser;
            return list.stream()
                    .filter(a -> a.getStudentId().equals(student.getId()))
                    .collect(Collectors.toList());
        }
        
        // 管理员和教师可以看到所有请假申请
        return list;
    }

    /**
     * 分页查询
     * 添加权限控制：学生只能查看自己的请假申请
     */
    public PageInfo<Apply> selectPage(Apply apply, Integer pageNum, Integer pageSize) {
        // 获取当前登录用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser != null && RoleEnum.STUDENT.name().equals(currentUser.getRole())) {
            // 学生只能看到自己的请假申请
            Student student = (Student) currentUser;
            apply.setStudentId(student.getId());
        }
        
        PageHelper.startPage(pageNum, pageSize);
        List<Apply> list = applyMapper.selectAll(apply);
        return PageInfo.of(list);
    }

}
